/*
 * serialTest.c:
 *	Very simple program to test the serial port. Expects
 *	the port to be looped back to itself
 *
 * Copyright (c) 2012-2013 Gordon Henderson. <projects@drogon.net>
 ***********************************************************************
 * This file is part of wiringPi:
 *	https://projects.drogon.net/raspberry-pi/wiringpi/
 *
 *    wiringPi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Lesser General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    wiringPi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public License
 *    along with wiringPi.  If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************
 */
#ifdef __cplusplus__
  #include <cstdlib>
#else
  #include <stdlib.h>
#endif
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>

#include <wiringPi.h>
#include <wiringSerial.h>
#include "updateState.h"

#define FIFO_NAME "/tmp/myfifo2"
#define TEN_MEG ( 1024*1024*10 )                      //文件缓冲区最大值
char rxbuf[100];//100个字节的缓冲
void read_pipe(int sfd)
{
  int pipe_fd;
  int res;
  int t = 0;
  char getbuf[10];
  int open_mode = O_RDONLY;

  pipe_fd = open(FIFO_NAME,open_mode);
  if(pipe_fd != -1)
  {
    while(1)
    {
      while((res = read(pipe_fd,getbuf,10))>0)
      {
        getbuf[res]=0;
        printf("%s",getbuf);
        for(t=0;t<res;t++)
          serialPutchar(sfd,getbuf[t]);
      }
      fflush(stdout);
    }
  }else{
    exit(1);
  }
  close(pipe_fd);
}

void write_pipe(char* c)
{
  int res;
  int pipe_fd;                  
  int bytes_send = 0;

  if( access(FIFO_NAME, F_OK) == -1 ) {       //F_OK : 检查是否有这个文件;  类似还有检查文件可读等，参见man中access中定义
    res = mkfifo(FIFO_NAME, 0777);                  //创建管道文件，文件属性为0777，root可读写
    if( res != 0 ){                                 //管道文件不可重名
      printf( "Could not create fifo %s \r\n", FIFO_NAME );
      exit( 1 );
    }
  }

  pipe_fd = open( FIFO_NAME, O_WRONLY );             //打开管道，并设置打开权限
  if( pipe_fd !=-1 ){


      res = write( pipe_fd, c, 2 );                       //向管道中写数据
      if( res == -1 ){
    perror( "write error" );
    close( pipe_fd );
    exit( 1 );
      }
    
    close( pipe_fd );
  }
  return 0;
}


void signal_handler( int n){                                 //受到子进程退出信号，结束子进程
  int child_status;
  wait( &child_status );
  printf( "child exited. \r\n" );
}

int main (int argc, char* argv[])
{
  int fd;
  int count;
  int rxflag;
  int pid;
  int child_status;
  int i=0;

  if ((fd = serialOpen ("/dev/ttyS1", 115200)) < 0)
  {
    fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
    return 1 ;
  }

  if (wiringPiSetup () == -1)
  {
    fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
    return 1 ;
  }

  //signal(SIGCHLD, signal_handler);                    //子进程退出时所发信号
  //unsigned int nextTime;
  //pid = fork();

  /*switch(pid)
  {
    case -1:
      printf("fork error.\r\n");
      exit(1);
    break;
    case 0:
      while(1)
      {
        read_pipe(fd);//读缓冲数据
      }
     // exit(1);
    break;
    default:
      for(i;i<100;i++){
        //write_pipe("ok");
        printf("%d\r\n", i);
        fflush( stdout );
        sleep(2);
      }
    break;
  }*/
  //return 0;


  
/****************example*****************/
  //nextTime = millis () + 300 ;

/*for (count = 0 ; count < 256 ; )
  {
    if (millis () > nextTime)
    {
      printf ("\nOut: %3d: ", count) ;
      fflush (stdout) ;
      serialPutchar (fd, count);
      nextTime += 300 ;
      ++count ;
    }

    delay (3) ;

    while (serialDataAvail (fd))
    {
      printf (" -> %3d", serialGetchar (fd)) ;
      fflush (stdout) ;
    }
  }*/
/*****************mytask*******************/
  count = 0;
  rxflag = 0;
  while(1)
  {
    read_pipe(fd);//读缓冲数据  
	/*if(serialDataAvail (fd))//有数据
	{
		char temp = serialGetchar(fd);
		rxbuf[count] = temp;
		count++;
		if(rxflag == 1)//接收到0x0d
		{
			if(temp == 0x0a)//判断是否是0x0a
			{
				rxflag = 0;//重新开始下一次接收
				rxbuf[count] = 0x00;//下一位置0
				count = 0;
        updateState(rxbuf);
        fflush(stdout);
			}else{
				rxflag = 0;
			}
		}else{//未获取0x0d
			if(temp == 0x0d)//获取到0x0d
			{
				rxflag = 1;
			}
		}
		if(count >= 100)//超出缓冲最大
		{
			count = 0;
			rxflag = 0;
		}
	}*/
	  
  }
  printf ("\n") ;
  return 0 ;
}
